package com.lazydong.apiforward.clientupdate.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class KillClientUtil {
    // 设置字符编码为 GBK（根据实际情况调整）
    private static final Charset charset = Charset.forName("GBK");

    public static void killByPid(String pid) {
        String cmd = "taskkill /pid %s -f";
        runCmd(null, String.format(cmd, pid));
    }


    public static void runCmd(String directoryPath, String cmd) {
        try {
            // 要执行的命令及其参数
            List<String> commands = new ArrayList<>();
            commands.add("cmd.exe");
            commands.add("/c");
            commands.add(cmd); // 示例命令：列出当前目录下的文件和子目录
            // 创建 ProcessBuilder 实例
            ProcessBuilder pb = new ProcessBuilder(commands);
            if (directoryPath != null) {
                pb.directory(new File(directoryPath));
            }
            // 启动进程
            Process process = pb.start();
            // 读取命令输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), charset));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 等待命令执行完成并获取退出码
            int exitCode = process.waitFor();
            System.out.println("Command exited with code: " + exitCode);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
